/* eslint-disable vue/valid-v-for */
<template>
  <div class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-row :gutter="13" type="flex">
        <el-col :span="2">
          <el-select v-model="selectSortValue" placeholder="请选择" @change="selectSort">
            <el-option
              v-for="item in sorts"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>

        <el-col :span="2">
          <el-select v-model="selectStatusValue" placeholder="请选择" @change="selectStatus">
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-select v-model="warehouseId" placeholder="全部仓库" class="seach-select" size="small">
          <el-option>全部仓库</el-option>
          <el-option
            v-for="item in apart_options"
            :key="item.warehouseId"
            :label="item.warehouseName"
            :value="item.warehouseId"
          />
        </el-select>

        <!-- @blur="searchSku" -->
        <el-col :span="4">
          <el-input v-model="search" placeholder="输入供应商.sku查询"/>
        </el-col>

        <el-col :span="2" class="lingkc">
          <input v-model="defect" type="checkbox">
          不显示0库存
        </el-col>
        <el-col :span="1">
          <el-button type="primary" @click="searchSku">查询</el-button>
        </el-col>

        <el-col :span="1" >
          <el-button type="primary" @click="download()">下载</el-button>
        </el-col>

        <!--  <el-col :span="1">
            <el-button
                type="primary"

                >编辑</el-button>
        </el-col>-->
      </el-row>
    </div>

    <!-- v-loading="listLoading" -->
    <el-table :data="stockList" border highlight-current-row style="width: 95%;">
      <el-table-column
        :formatter="formatterClassification"
        prop="classification"
        label="分类"
        min-width="5%"
      />
      <el-table-column prop="skuCode" label="SKU编码" min-width="10%"/>
      <el-table-column prop="skuName" label="SKU名称" min-width="20%"/>
      <el-table-column prop="warehouseName" label="仓库" min-width="15%"/>
      <el-table-column prop="systemStock" label="系统库存" min-width="10%">
        <template slot-scope="scope">
          <span style="color:blue" @click="serialNumber(scope.row.stockId,scope.row.warehouseName,scope.row.skuName)">{{ scope.row.systemStock }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :formatter="availableAmountProcess"
        prop="systemStock"
        label="可用库存"
        min-width="10%"
      />
      <el-table-column prop="onTheWayAmount" label="在途量" min-width="10%"/>
      <el-table-column prop="lockAmount" label="锁定量" min-width="10%"/>
      <el-table-column
        :formatter="formatterRmb.bind(null,'unitPrice')"
        prop="unitPrice"
        label="库存单价"
        min-width="10%"
      />
      <el-table-column
        :formatter="formatterRmb.bind(null,'lnventoryCosts')"
        prop="lnventoryCosts"
        label="库存成本"
        min-width="10%"
      />
      <el-table-column prop="daynum" label="库龄" min-width="10%"/>
      <el-table-column prop="fdl" label="浮动率" min-width="10%"/>
    </el-table>

    <!--分页-->
    <div class="pagination-container">
      <el-pagination
        v-show="total>0"
        :current-page="listQuery.page"
        :page-sizes="[10,20,30, 50]"
        :page-size="listQuery.pageSize"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog :visible.sync="dialogTableVisible" title="" width="20%">
      <span class="jiachu">仓库名：  {{ warehouseName }}</span><br><br>
      <span class="jiachu">SKU名称：  {{ skuName }}</span>
      <el-table :data="gridData" >
        <el-table-column property="serialNumber" label="序列号：" width="200"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
// post,
import { get } from '@/api/utils'
import { distributorList } from '@/api/payment'
import { parseTime } from '@/utils'

export default {
  data() {
    // var validateNumber = (rule, value, callback) => {
    //   if (!Number(value)) {
    //     callback(new Error('请输入数字值'))
    //   } else {
    //     const regu = /^[0-9]+[\.][0-9]{0,3}$/
    //     const rsCheck = regu.test(value)
    //     if (!rsCheck) {
    //       callback(new Error('请输入正确的金额类型'))
    //     }
    //     callback()
    //   }
    // }
    return {
      sorts: [
        { value: '1', label: '整机' },
        { value: '2', label: '工具' },
        { value: '3', label: '辅材' },
        { value: '4', label: '赠品' }
      ],

      statusList: [
        { value: '1', label: '正常' },
        { value: '2', label: '停采' },
        { value: '3', label: '停用' }
      ],
      selectSortValue: null,
      selectStatusValue: null,
      search: '',
      selectName: '请选择',
      dialogTableVisible: false,
      partnerList: [
        {
          value: 'partner-73250',
          text: '美博'
        },
        {
          value: 'partner-73251',
          text: '长沙供应商'
        }
      ],
      dialogFormVisible: false,
      gridData: [],
      warehouseName: '',
      skuName: '',
      stockList: [],
      //       {
      // "sku_id":1,
      // "sku_name":"test",
      // "sku_code":"test",
      // "category_id":1,
      // "category_name":"test",
      // "accessory_model":"test",
      // "supplier_id":1,
      // "supplier_name":"test",
      // "varieties_id":null,
      // "varieties_name":null,
      // "material_type":null,
      // "classification":1,
      // "purchase_price":1.00,
      // "sales_type":1,
      // "brand_name":"test",
      // "brand_id":"1",
      // "status":1,
      // "image_url":null,
      // "international_barcode":null,
      // "creater_id":null,
      // "create_datetime":null,
      // "delete_datetime":null,
      // "delete_remark":null,
      // "deleter_id":null,
      // "delete_flag":"Y",
      // "update_datetime":null,
      // "updater_id":null
      // }
      total: 1,
      listLoading: true,
      offset: 0,
      limit: 10,
      listQuery: {
        page: 1,
        pageSize: 10,
        keyword: null,
        starTime: null,
        endTime: null,
        shipmentNo: null,
        time: null,
        pageNumber: null
      },
      warehouseId: '',
      apart_options: [],
      defect: '',
      time: ''
    }
  },
  created() {
    this.getSkuList()
    this.getWarehouse()
  },

  methods: {
    getWarehouse: function() {
      var param = {}
      param.warehouseId = this.warehouseId
      get('/wxh-cloud-rest/rest/', '/pas/warehouse/queryList', param)
        .then(response => {
          this.apart_options = response.data.data.list
        })
    },
    download: function() {
      var param = {}
      if (this.selectSortValue !== null) {
        param.classification = this.selectSortValue
      }
      if (this.selectStatusValue !== null) {
        param.status = this.selectStatusValue
      }
      if (this.search !== null) {
        param.search = this.search
      }
      if (this.warehouseId != null) {
        param.warehouseId = this.warehouseId
      }

      param.defect = this.defect
      get('/wxh-cloud-rest/rest/', '/pas/stock/downloadStock', param)
        .then(response => {
          const date = new Date()
          const filefix =
            date.getFullYear() +
            '-' +
            parseInt(date.getMonth() + 1) +
            '-' +
            date.getDate() +
            ' ' +
            date.getHours() +
            ':' +
            date.getMinutes() +
            ':' +
            date.getSeconds()
          const blob = new Blob([response.data], {
            type: 'text/csvchartset=utf-8' // 将会被放入到blob中的数组内容的MIME类型
          }) // 创建一个blob对象
          const a = document.createElement('a') // 创建一个<a></a>标签
          a.href = URL.createObjectURL(blob) // response is a blob
          a.download = filefix + '库存.csv' // 文件名称
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          a.remove()
          return response
        })
        .catch(error => {
          console.log(error)
        })
    },

    serialNumber(stockId, warehouseName, skuName) {
      this.skuName = skuName
      this.warehouseName = warehouseName
      var data = {
        stockId: stockId
      }
      get('/wxh-cloud-rest/rest/', '/pas/stock/getSerialNumberList', data)
        .then(response => {
          if (response.data.status === 'success') {
            this.gridData = response.data.data.list
          }
        })
      this.dialogTableVisible = true
    },
    formatterClassification(row, column) {
      if (row.classification) {
        if (row.classification === 1) {
          return '整机'
        } else if (row.classification === 2) {
          return '工具'
        } else if (row.classification === 3) {
          return '辅材'
        } else if (row.classification === 4) {
          return '赠品'
        }
      }
    },
    formatterStatus(row, column) {
      if (row.status) {
        if (row.status === 1) {
          return '正常'
        } else if (row.status === 2) {
          return '停采'
        } else if (row.status === 1) {
          return '停用'
        }
      }
    },
    formatterSalesType(row, column) {
      if (row.salesType) {
        if (row.salesType === 1) {
          return '供应商代发'
        } else if (row.salesType === 2) {
          return '其他'
        }
      }
    },
    availableAmountProcess(row, column) {
      row.systemStock = row.systemStock !== null ? row.systemStock : 0
      row.lockAmount = row.lockAmount !== null ? row.lockAmount : 0
      return row.systemStock - row.lockAmount
    },
    formatterRmb(field, row, column) {
      if (field) {
        return '￥' + row[field]
      }
    },

    getSkuList() {
      this.listLoading = true
      this.listQuery.pageNumber =
        (this.listQuery.page - 1) * this.listQuery.pageSize

      var data = {
        offset: this.listQuery.pageNumber,
        limit: this.listQuery.pageSize
      }

      if (this.selectSortValue !== null) {
        data.classification = this.selectSortValue
      }

      if (this.selectStatusValue !== null) {
        data.status = this.selectStatusValue
      }

      if (this.search !== null) {
        data.search = this.search
      }
      if (this.warehouseId != null) {
        data.warehouseId = this.warehouseId
      }

      data.defect = this.defect
      get('/wxh-cloud-rest/rest/', '/pas/stock/list', data)
        .then(response => {
          if (response.data.status === 'success') {
            console.log(
              '-------------------------------------------------------------'
            )
            this.total = response.data.data.count
            this.stockList = response.data.data.stockList

            this.listLoading = false
          } else if (response.data.status === 'token_check_faild') {
            this.$message({
              message: response.data.messge,
              type: 'warning'
            })
            this.listLoading = false
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '数据加载失败',
            type: 'warning'
          })
          this.listLoading = false
        })
    },

    selectSort(event) {
      this.selectSortValue = event
      this.listQuery.page = 1
      this.getSkuList()
    },
    selectStatus(event) {
      this.selectStatusValue = event
      this.listQuery.page = 1

      this.getSkuList()
    },

    searchSku(event) {
      // console.log(event)
      this.listQuery.page = 1
      this.getSkuList()
    },

    // getList() {
    //   this.listLoading = true
    //   this.listQuery.pageNumber =
    //     (this.listQuery.page - 1) * this.listQuery.pageSize

    //   fetchList(this.listQuery)
    //     .then(response => {
    //       if (response.data.status === 'success') {
    //         this.total = response.data.data.total
    //         this.talelist = response.data.data.list
    //         this.listLoading = false
    //       } else if (response.data.status === 'token_check_faild') {
    //         this.$message({
    //           message: response.data.messge,
    //           type: 'warning'
    //         })
    //         this.listLoading = false
    //       }
    //     })
    //     .catch(error => {
    //       console.log(error)
    //       this.$message({
    //         message: '数据加载失败',
    //         type: 'warning'
    //       })
    //       this.listLoading = false
    //     })
    // },
    // 查询分销商
    getDistributorList() {
      distributorList().then(response => {
        this.disList = response.data.data
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getSkuList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getSkuList()
    },
    searchFrom() {
      if (this.listQuery.time !== null && this.listQuery.time !== '') {
        this.listQuery.starTime = parseTime(
          this.listQuery.time[0],
          '{y}-{m}-{d} {h}:{i}'
        )
        this.listQuery.endTime = parseTime(
          this.listQuery.time[1],
          '{y}-{m}-{d} {h}:{i}'
        )
      } else {
        this.listQuery.starTime = null
        this.listQuery.endTime = null
      }
      this.listQuery.pageNumber = 0
      this.getList()
    },
    cancelEdit(row) {
      row.edit = false
      this.$message({
        message: '取消成功',
        type: 'warning'
      })
    }

    // deleteShipmentByShipmentNo(val) {
    //   var data = {
    //     shipmentNo: val.shipmentNo
    //   }
    //   this.$confirm('此操作将永久删除该单据, 是否继续?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       deleteShipmentByShipmentNo(data)
    //         .then(response => {
    //           if (response.data.status === 'ok') {
    //             this.getList()
    //             this.$message({
    //               message: '删除成功',
    //               type: 'success'
    //             })
    //           } else {
    //             this.$message({
    //               message: '删除失败',
    //               type: 'warning'
    //             })
    //           }
    //         })
    //         .catch(error => {
    //           this.$message({
    //             message: '删除失败',
    //             type: 'warning'
    //           })
    //           console.log(error)
    //         })
    //     })
    //     .catch(() => {
    //       this.$message({
    //         type: 'info',
    //         message: '已取消删除'
    //       })
    //     })
    // },

    // recoveryArchivesByshipmentNo(val) {
    //   var data = {
    //     shipmentNo: val.shipmentNo
    //   }
    //   this.$confirm('回收单据后将无法修改, 是否继续?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       recoveryArchivesByshipmentNo(data)
    //         .then(response => {
    //           if (response.data.status === 'ok') {
    //             this.getList()
    //             this.$message({
    //               message: '回收成功',
    //               type: 'success'
    //             })
    //           } else {
    //             this.$message({
    //               message: '回收失败',
    //               type: 'warning'
    //             })
    //           }
    //         })
    //         .catch(error => {
    //           this.$message({
    //             message: '回收失败',
    //             type: 'warning'
    //           })
    //           console.log(error)
    //         })
    //     })
    //     .catch(() => {
    //       this.$message({
    //         type: 'info',
    //         message: '已取消回收'
    //       })
    //     })
    // },

    // generateShipmentByNo(val) {
    //   if (val.recordStatus === 'Y') {
    //     this.$message({
    //       message: '该出入单据已经生成',
    //       type: 'success'
    //     })
    //     return
    //   } else if (val.archivesFlag === 'Y') {
    //     this.$message({
    //       message: '该单据已回收,不能生成',
    //       type: 'success'
    //     })
    //     return
    //   }
    //   var data = {
    //     shipmentNo: val.shipmentNo
    //   }
    //   this.$confirm('该操作将根据发货单号生成出入库记录, 是否继续?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       generateShipmentByNo(data)
    //         .then(response => {
    //           if (response.data.status === 'ok') {
    //             this.getList()
    //             this.$message({
    //               message: '生成成功',
    //               type: 'success'
    //             })
    //           } else {
    //             this.$message({
    //               message: '生成失败',
    //               type: 'warning'
    //             })
    //           }
    //         })
    //         .catch(error => {
    //           this.$message({
    //             message: '生成失败',
    //             type: 'warning'
    //           })
    //           console.log(error)
    //         })
    //     })
    //     .catch(() => {
    //       this.$message({
    //         type: 'info',
    //         message: '已取消'
    //       })
    //     })
    // },

    // deleteDetail(row) {
    //   var data = {
    //     materialDetailId: row.materialDetailId
    //   }
    //   this.$confirm('此操作将永久删除该物资明细, 是否继续?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       deleteDetailByid(data)
    //         .then(response => {
    //           if (response.data.status === 'ok') {
    //             this.getList()
    //             this.$message({
    //               message: '删除成功',
    //               type: 'success'
    //             })
    //           } else {
    //             this.$message({
    //               message: '删除失败',
    //               type: 'warning'
    //             })
    //           }
    //         })
    //         .catch(error => {
    //           this.$message({
    //             message: '删除失败',
    //             type: 'warning'
    //           })
    //           console.log(error)
    //         })
    //     })
    //     .catch(() => {
    //       this.$message({
    //         type: 'info',
    //         message: '已取消删除'
    //       })
    //     })
    // },

    // confirmEdit(row) {
    //   row.edit = false
    //   var data = {
    //     materialDetailId: row.materialDetailId,
    //     productCnt: row.productCnt,
    //     productPrice: row.productPrice,
    //     shipmentNo: row.shipmentNo
    //   }
    //   updateDetailByid(data)
    //     .then(response => {
    //       if (response.data.status === 'ok') {
    //         this.getMaterialDetails(row)
    //         this.getList()
    //         this.$message({
    //           message: '修改成功',
    //           type: 'success'
    //         })
    //       } else {
    //         this.$message({
    //           message: '修改失败',
    //           type: 'warning'
    //         })
    //       }
    //     })
    //     .catch(error => {
    //       this.$message({
    //         message: '修改失败',
    //         type: 'warning'
    //       })
    //       console.log(error)
    //     })
    // },

    // getShipmentNo(val) {
    //   this.shipmentNo = val
    // },

    // 导入
    // excelUpload(item) {
    //   var formData = new FormData()
    //   formData.append('importExcel', item.file)
    //   formData.append('shipmentNo', this.shipmentNo)
    //   importMaterialDetails(formData).then(response => {
    //     if (response.data.status === 'success') {
    //       this.getList()
    //       this.$message('导入成功')
    //     } else {
    //       this.$message('导入失败')
    //     }
    //   })
    // },

    // addDetail() {
    //   // 添加表单
    //   this.dynamicValidateForm.details.push({
    //     productName: '',
    //     productSpecifications: '',
    //     productCnt: '',
    //     productAmount: '',
    //     productCategory: '',
    //     productBrand: '',
    //     productPrice: '',
    //     productUnit: ''
    //   })
    // },

    // removeDetail(item) {
    //   // 删除表单
    //   var index = this.dynamicValidateForm.details.indexOf(item)
    //   if (index !== -1) {
    //     this.dynamicValidateForm.details.splice(index, 1)
    //   }
    // },

    // submitForm(formName) {
    //   // 提交集合表单
    //   this.$refs[formName].validate(valid => {
    //     if (valid) {
    //       var time = parseTime(
    //         this.dynamicValidateForm.shipmentCreateDatetime,
    //         '{y}-{m}-{d}'
    //       )
    //       this.dynamicValidateForm.shipmentCreateDatetime = time

    //       var disName
    //       for (var i = 0; i < this.disList.length; i++) {
    //         if (this.disList[i].disId === this.dynamicValidateForm.disId) {
    //           disName = this.disList[i].disName
    //         }
    //       }
    //       this.dynamicValidateForm.disName = disName

    //       var partnerName
    //       for (var j = 0; j < this.partnerList.length; j++) {
    //         if (
    //           this.partnerList[j].value === this.dynamicValidateForm.partnerId
    //         ) {
    //           partnerName = this.partnerList[j].text
    //         }
    //       }
    //       this.dynamicValidateForm.partnerName = partnerName
    //       console.log(
    //         '===========' +
    //           JSON.stringify(this.$refs['dynamicValidateForm'].model)
    //       )
    //       this.detailsJson = JSON.stringify(
    //         this.$refs['dynamicValidateForm'].model
    //       )
    //       var param = {
    //         detailsJson: this.detailsJson
    //       }
    //       addShipmentAndDetails(param)
    //         .then(response => {
    //           if (response.data.status === 'success') {
    //             this.$message({
    //               message: '添加成功',
    //               type: 'success'
    //             })
    //             setTimeout(() => {
    //               this.dialogFormVisible = false
    //             }, 1.5 * 1000)
    //             this.getList()
    //           } else {
    //             this.$message({
    //               message: '添加失败：' + response.data.messge,
    //               type: 'error'
    //             })
    //           }
    //         })
    //         .catch(error => {
    //           console.log(error)
    //           this.listLoading = false
    //         })
    //     } else {
    //       console.log('error submit!!')
    //       return false
    //     }
    //   })
    // },

    // resetForm(item) {
    //   // 清空表单
    //   var index = this.dynamicValidateForm.details.indexOf(item)
    //   if (index !== -1) {
    //     this.dynamicValidateForm.details.splice(index, 1, {
    //       productName: '',
    //       productSpecifications: '',
    //       productCnt: '',
    //       productAmount: '',
    //       productCategory: '',
    //       productBrand: '',
    //       productPrice: '',
    //       productUnit: ''
    //     })
    //   }
    // },

    // dialogCancle() {
    //   this.dialogFormVisible = false
    //   this.dynamicValidateForm = {
    //     disId: null,
    //     partnerName: null,
    //     shipmentNo: null,
    //     productTotalAmount: null,
    //     createDatetime: null,
    //     details: [
    //       {
    //         productName: '',
    //         productSpecifications: '',
    //         productCnt: '',
    //         productAmount: '',
    //         productCategory: '',
    //         productBrand: '',
    //         productPrice: '',
    //         productUnit: ''
    //       }
    //     ]
    //   }
    // }
  }
}
</script>
<style>
.jiachu{
  font-weight: bold;
}
.lingkc{
  font-size: 13px;
  line-height: 40px;
}
</style>

